package netdb.courses.softwarestudio.event;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class CommentServlet extends HttpServlet {
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        Key eventKey = KeyFactory.createKey("EventKind", "event");
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        //use id to identify Event
        Query query = new Query("Event", eventKey).addFilter("id", FilterOperator.EQUAL, req.getParameter("id"));
        List<Entity> events = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
        events.get(0).setProperty("comment", req.getParameter("comment"));
        datastore.put(events);
        resp.getWriter().write(toJson(events));
	}
	private String toJson(List<Entity> events){
    	JSONArray array = new JSONArray();
    	for (Entity event : events) {
    		JSONObject jsonObj=new JSONObject();
    		jsonObj = new JSONObject();
    		for(String propertyName:event.getProperties().keySet()){
    			String propertyValue;
    			if(event.getProperty(propertyName)!=null){
    				propertyValue =event.getProperty(propertyName).toString();
    			}
    			else{
    				propertyValue="idiot";
    			}
    			try {
					jsonObj.put(propertyName,propertyValue);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		} 
            array.put(jsonObj); 
    	}
    	return array.toString();
    }
}